<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\admin\model\SalesShipment;

/**
 * 对账单
 *
 * @icon fa fa-circle-o
 */
class SaleDelivery extends Backend
{

    /**
     * SaleDelivery模型对象
     * @var \app\admin\model\SaleDelivery
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\SaleDelivery;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }

        // 如果发送的来源不是 Selectpage，则使用 SalesShipment 模型查询数据
        $salesShipmentModel = new SalesShipment();
        $list = $salesShipmentModel->select();

        $rows = [];
        foreach ($list as $item) {
            $customerDemandJson = json_decode($item['customer_demand_json'], true);
            if (is_array($customerDemandJson)) {
                foreach ($customerDemandJson as $demand) {
                    $rows[] = [
                        'order_id' => $item['order_id'],
                        'createtime' => $item['created_at'],
                        'updatetime' => $item['updated_at'],
                        'remarks' => $item['remarks'],
                        'product_id' => $demand['product_id'] ?? null,
                        'customer_id' => $demand['customer_id'] ?? null,
                        'product_name' => $demand['product_name'] ?? null,
                        'customer_name' => $demand['customer_name'] ?? null,
                        'quantity' => $demand['quantity'] ?? null,
                    ];
                }
            }
        }

        $result = ['total' => count($rows), 'rows' => $rows];
        return json($result);
    }


}
